<template>
  <div>
    <el-form>
      <el-form-item class="crm-create-item" style="padding-left: 25px;margin-bottom:0" required>
        <div
          slot="label"
          style="display: inline-block;line-height: 0">
          <div style="margin:5px 0;font-size:12px;word-wrap:break-word;word-break:break-all;">
            {{ showText.title }}
          </div>
        </div>
      </el-form-item>
    </el-form>
    <flexbox justify="flex-end">
      <CrmRelativeCell :item="cellData" :is-define="true" :value="pageData" @value-change="selectFile">
        <template slot="defineButton">
          <el-button type="primary">上传</el-button>
        </template>
      </CrmRelativeCell>
      <el-button type="warning" style="margin-left: 10px;" @click="sort(true)">排序</el-button>
    </flexbox>
    <el-card :shadow="isSort ? 'always': 'never'" >
      <div v-if="isSort" slot="header" class="clearfix">
        <span>{{ showText.sortTitle }}</span>
      </div>
      <el-table
        v-loading="loading"
        id="source-table"
        :data="pageData"
        :max-height="tableHeight"
        :cell-style="cellStyle"
        class="n-table--border"
        stripe
        border
        highlight-current-row
        style="width: 100%;margin-top: 10px;">
        <el-table-column
          v-for="(item, index) in newfieldList"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          :show-overflow-tooltip="item.label == '序号' ? false : true">
          <template
            slot-scope="scope">
            <div v-if="item.label == '序号'">
              <template v-if="isSort">
                <input v-model="scope.row[item.prop]" type="number" class="el-input__inner el-input">
              </template>
              <template v-else>
                {{ scope.row[item.prop] | time(item.prop) }}
              </template>
            </div>
            <div v-else :title="scope.row[item.prop]" class="table-head-name">{{ scope.row[item.prop] | time(item.prop) }}</div>
          </template>
        </el-table-column>
      </el-table>
      <template v-if="isSort">
        <flexbox style="justify-content: flex-end;margin-top: 10px;">
          <el-button @click="sort(false)">取消</el-button>
          <el-button type="primary" @click="saveTable">确定</el-button>
        </flexbox>
      </template>
      <el-pagination
        :current-page="currentPage"
        :page-sizes="pageSizes"
        :page-size.sync="pageSize"
        :total="total"
        class="p-bar"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
    </el-card>
  </div>
</template>
<style lang="scss" scoped>
.el-card {
  border:0;
  .el-card__body {
    padding: 0;
  }
}

</style>
<script>
import {
  mapGetters
} from 'vuex'
import { getSourceFileList } from '../../../api/kmsmanagement/source'
import { getCourseSourceList } from '../../../api/kmsmanagement/course'
import {
  filedGetTableField
} from '@/api/financemanagement/common'
import kmsTypeModel from '@/views/kmsmanagement/model/kmsTypeModels'
import CrmRelativeCell from '../../../components/CreateCom/CrmRelativeCell'
export default {
  name: 'RelativeSource',
  components: {
    CrmRelativeCell
  },
  props: {
    action: {
      type: Object, default: () => {
        return {
          type: 'ave',
          id: '',
          data: {} // 编辑所需信息
        }
      }
    },
    sortId: {
      type: String,
      default: ''
    },
    kmsType: {
      type: String,
      default: ''
    },
    sourceList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      isSort: false,
      loading: false,
      tableHeight: 400, // 表的高度
      list: [],
      fieldList: [],
      sortIndex: [],
      currentPage: 1,
      pageSize: 20,
      pageSizes: [5, 10, 20, 50],
      total: 0,
      pageData: []
    }
  },
  computed: {
    ...mapGetters(['kms']),
    newfieldList() {
      const list = JSON.parse(JSON.stringify(this.fieldList))
      list.unshift({
        prop: '序号',
        label: '序号'
      })
      return list
    },
    cellData() {
      if (this.kmsType == 'resource') {
        return {
          data: {
            formType: 'kmsSource'
          }
        }
      }
      if (this.kmsType == 'course') {
        return {
          data: {
            formType: 'kmsCourse'
          }
        }
      }
    },
    showText() {
      if (this.kmsType == 'resource') {
        return {
          title: '文件上传',
          sortTitle: '对文件排序'
        }
      }
      if (this.kmsType == 'course') {
        return {
          title: '学习资源',
          sortTitle: '对资源排序'
        }
      }
    }
  },
  // eslint-disable-next-line vue/order-in-components
  filters: {
    time(val, prop) {
      if (prop != 'standardStudySeconds') {
        return val
      }
      val = Number(val)
      var sec = parseInt(val / 60)
      var min = Number((val - sec * 60) / 60)
      // eslint-disable-next-line no-unused-vars
      var res = Math.ceil(Number(min.toFixed(2)) * 10) / 10
      return sec + res
    }
  },
  watch: {
    list: {
      handler(val) {
        val.forEach((item, index) => {
          item['序号'] = index + 1
        })
        this.saveTable()
      },
      immediate: true
    },
    sourceList: {
      handler(val) {
        this.list = val
        this.total = val.length
        this.handleCurrentChange(1)
      },
      immediate: true
    }
  },
  mounted() {
    if (this.kms[this.kmsType].index) {
      this.loading = true
      this.getFieldList()
    }
  },
  methods: {
    /** 通过回调控制style */
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (column.property === 'name') {
        return { color: '#3E84E9', cursor: 'pointer' }
      } else {
        return ''
      }
    },
    sort(val) {
      this.isSort = val
    },
    /** 获取列表数据 */
    getList(val) {
      this.loading = true
      const url = this.getListUrl()
      url(val)
        .then(res => {
          this.list = res.data
          this.total = res.data.length
          this.handleCurrentChange(1)
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    getListUrl() {
      if (this.kmsType == 'resource') {
        return getSourceFileList
      }
      if (this.kmsType == 'course') {
        return getCourseSourceList
      }
    },
    /** 获取字段 */
    getFieldList(val) {
      this.fieldList = []
      if (this.fieldList.length == 0) {
        this.loading = true
        filedGetTableField({
          label: this.kmsType == 'resource' ? 100 : 101
        })
          .then(res => {
            for (let index = 0; index < res.data.length; index++) {
              const element = res.data[index]
              var width = 0
              if (!element.width) {
                if (element.name && element.name.length <= 6) {
                  width = element.name.length * 15 + 45
                } else {
                  width = 140
                }
              } else {
                width = element.width
              }
              this.fieldList.push({
                prop: element.fieldName,
                label: element.name,
                width: width
              })
            }
            // 获取好字段开始请求数据
            if (this.action.type == 'update') {
              const param = this.kmsType == 'resource' ? { resourceId: this.action.id } : { courseId: this.action.id }
              this.getList(param)
            } else {
              this.loading = false
            }
          })
          .catch(() => {
            this.loading = false
          })
      } else {
        // 获取好字段开始请求数据
        this.getList()
      }
    },
    saveTable() {
      const res = []
      this.list.forEach(item => {
        const params = { sort: item['序号'] }
        const id = this.sortId == 'file_id' ? 'fileId' : 'resourceId'
        params[this.sortId] = item[id]
        res.push(params)
      })
      this.$emit('value-change', res)
      this.sort(false)
    },
    selectFile(data) {
      this.list = data.value
      this.total = data.value.length
      this.handleCurrentChange(1)
    },
    // 更改每页展示数量
    handleSizeChange(val) {
      this.pageSize = val
      this.handleCurrentChange(1)
    },
    // 更改当前页数
    handleCurrentChange(val) {
      this.currentPage = val
      const start = (val - 1) * this.pageSize
      const end = val * this.pageSize
      this.pageData = this.list.slice(start, end)
    },
    changeList(data) {
      this.list = data
    }
  }
}
</script>
